/**********************************************************************************************************************
 * \file Cpu0_Main.c
 * \copyright Copyright (C) Infineon Technologies AG 2019
 * 
 * Use of this file is subject to the terms of use agreed between (i) you or the company in which ordinary course of 
 * business you are acting and (ii) Infineon Technologies AG or its licensees. If and as long as no such terms of use
 * are agreed, use of this file is subject to following:
 * 
 * Boost Software License - Version 1.0 - August 17th, 2003
 * 
 * Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and 
 * accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute,
 * and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the
 * Software is furnished to do so, all subject to the following:
 * 
 * The copyright notices in the Software and this entire statement, including the above license grant, this restriction
 * and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all 
 * derivative works of the Software, unless such copies or derivative works are solely in the form of 
 * machine-executable object code generated by a source language processor.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE 
 * COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN 
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE.
 *********************************************************************************************************************/
#include "Ifx_Types.h"
#include "IfxCpu.h"
#include "IfxScuWdt.h"
#include "rtthread.h"

IFX_ALIGN(4) IfxCpu_syncEvent g_cpuSyncEvent = 0;

/* 调试状态变量 - 全局可见 */
volatile rt_uint32_t system_status = 0x0000;
volatile rt_uint32_t hardware_test_counter = 0;

/* RT-Thread任务相关定义 */
/* 任务1：LED控制任务 */
static rt_uint8_t task1_stack[8192];
static struct rt_thread task1_thread;
static rt_uint32_t task1_counter = 0;

/* 任务2：数据处理任务 */
static rt_uint8_t task2_stack[8192];
static struct rt_thread task2_thread;
static rt_uint32_t task2_counter = 0;

/* 外部函数声明 */
extern int rtthread_startup(void);

/* 任务入口函数声明 */
void task1_entry(void *parameter);
void task2_entry(void *parameter);
void init_user_tasks(void);

/* 任务1：LED控制任务入口函数 */
void task1_entry(void *parameter)
{
    task1_counter = 0x3333; /* 标记任务1开始执行 */
    
    while(1)
    {
        task1_counter++;
        
        /* LED控制逻辑 - 模拟LED闪烁 */
        if(task1_counter % 2 == 0)
        {
            /* LED ON状态 */
            system_status = (system_status & 0xFF00) | 0x00FF;
        }
        else
        {
            /* LED OFF状态 */
            system_status = (system_status & 0xFF00) | 0x0000;
        }
        
//        /* 任务延时 - 减少到200ms让出更多CPU时间 */
        rt_thread_yield();  /* 主动让出CPU */
        rt_thread_mdelay(200);
    }
}

void task2_entry(void *parameter)
{
    task2_counter = 0x4444; /* 标记任务2开始执行 */
    
    while(1)
    {
        task2_counter++;
        
        /* 数据处理逻辑 - 模拟数据采集和处理 */
        volatile rt_uint32_t sensor_data = task2_counter * 123 + 456;
        
        /* 更新系统状态的高字节部分 */
        system_status = (system_status & 0x00FF) | ((task2_counter & 0xFF) << 8);
        
        /* 简单的数据验证 */
        if(sensor_data > 10000)
        {
            /* 数据异常标记 */
            task2_counter = (task2_counter & 0xFFFF0000) | 0x9999;
        }
        
//        /* 任务延时 - 减少到300ms */
        rt_thread_yield();  /* 主动让出CPU */
        rt_thread_mdelay(300);
    }
}

#define THREAD_STACK_SIZE   4096      //????
#define THREAD_PRIORITY     20        //????????
#define THREAD_TIMESLICE    10        //???????
/* 初始化用户任务的函数 */
void init_user_tasks(void)
{
    rt_err_t result1, result2;

    /* 标记函数被调用 */
    task1_counter = 0xAAAA;
    task2_counter = 0xBBBB;

    /* 初始化任务1：LED控制任务 */
    result1 = rt_thread_init(&task1_thread,
                           "led_task",           /* 任务名称 */
                           task1_entry,          /* 任务入口函数 */
                           RT_NULL,              /* 任务参数 */
                           &task1_stack[0],      /* 任务栈起始地址 */
                           sizeof(task1_stack),  /* 任务栈大小 */
                           20,                    /* 任务优先级 */
                           10);                  /* 任务时间片 */

    if(result1 == RT_EOK)
    {
        result1 = rt_thread_startup(&task1_thread);
        if(result1 == RT_EOK)
        {
            task1_counter = 0x1111; /* 标记任务1已启动 */
        }
        else
        {
            task1_counter = 0xEEE1; /* 标记任务1启动失败 */
        }
    }
    else
    {
        task1_counter = 0xFFF1; /* 标记任务1初始化失败 */
    }

    /* 初始化任务2：数据处理任务 */
    result2 = rt_thread_init(&task2_thread,
                           "data_task",          /* 任务名称 */
                           task2_entry,          /* 任务入口函数 */
                           RT_NULL,              /* 任务参数 */
                           &task2_stack[0],      /* 任务栈起始地址 */
                           sizeof(task2_stack),  /* 任务栈大小 */
                           20,                    /* 任务优先级 */
                           10);                  /* 任务时间片 */

    if(result2 == RT_EOK)
    {
        result2 = rt_thread_startup(&task2_thread);
        if(result2 == RT_EOK)
        {
            task2_counter = 0x2222; /* 标记任务2已启动 */
        }
        else
        {
            task2_counter = 0xEEE2; /* 标记任务2启动失败 */
        }
    }
    else
    {
        task2_counter = 0xFFF2; /* 标记任务2初始化失败 */
    }
}
INIT_APP_EXPORT(init_user_tasks);

void core0_main(void)
{
    // 标记：进入main函数
    system_status = 0x1000;
    hardware_test_counter = 0;
    
    IfxCpu_enableInterrupts();
    
    // 标记：中断已启用
    system_status = 0x1001;
    
    /* !!WATCHDOG0 AND SAFETY WATCHDOG ARE DISABLED HERE!!
     * Enable the watchdogs and service them periodically if it is required
     */
    IfxScuWdt_disableCpuWatchdog(IfxScuWdt_getCpuWatchdogPassword());
    IfxScuWdt_disableSafetyWatchdog(IfxScuWdt_getSafetyWatchdogPassword());
    
    // 标记：看门狗已禁用
    system_status = 0x1002;
    
    /* Wait for CPU sync event */
    IfxCpu_emitEvent(&g_cpuSyncEvent);
    IfxCpu_waitEvent(&g_cpuSyncEvent, 1);
    
    // 标记：CPU同步完成
    system_status = 0x1003;
    
    // **阶段2测试：启动RT-Thread但不创建用户线程**
    system_status = 0x3000; // 标记：准备启动RT-Thread
    
    rtthread_startup();
    
    // 如果RT-Thread启动成功，控制权交给调度器，此处代码不会执行
    // 如果执行到这里，说明RT-Thread启动失败
    system_status = 0x3999; // 标记：RT-Thread启动失败
    
    /* 备用循环：如果RT-Thread启动失败 */
    while(1)
    {
        rt_thread_mdelay(300);
//        hardware_test_counter++;
//
//        // 每100万次循环更新一次状态
//        if(hardware_test_counter % 1000000 == 0)
//        {
//            system_status = 0x4000 + (hardware_test_counter / 1000000);
//        }
//
//        // 简单延时
//        volatile int delay;
//        for(delay = 0; delay < 1000; delay++);
    }
}
